import Food from './Food'
import ScorePanel from './ScorePanel'
import Snake from './Snake'

class GameControl{
    snake:Snake
    food:Food
    scorePanel:ScorePanel
    direction:string = ''
    isLive = true
    constructor(){
        this.snake = new Snake()
        this.food = new Food()
        this.scorePanel = new ScorePanel()
        const d = Math.round(Math.random())
        this.direction = d ? 'Right' : 'Down'
        this.init()
    }
    init(){
        document.addEventListener('keydown', this.keydownHandler.bind(this))
        this.run()
    }
    // 键盘事件
    keydownHandler(event: KeyboardEvent){
        /**
         * event.key
         * chrome ArrowUp ArrowDown ArrowLeft ArrowRight
         * ie Up Down Left Right
         */
        let type = event.key || event.code
        if (type.indexOf('Up')>-1||type.indexOf('Down')>-1||type.indexOf('Left')>-1||type.indexOf('Right')>-1){
            this.direction = type.replace('Arrow', '')
        }
    }
    // 移动
    run(){
        let x = this.snake.X
        let y = this.snake.Y
        switch(this.direction){
            case 'Up':
                y -= 10
                break
            case 'Down':
                y += 10
                break
            case 'Left':
                x -= 10
                break
            case 'Right':
                x += 10
                break
            default:
                break
        }
        this.checkEat(x, y)
        try{
            this.snake.X = x
            this.snake.Y = y
            this.isLive && setTimeout(this.run.bind(this), 300 - (this.scorePanel.level-1)*30)
        }catch(e){
            alert(e)
        }
    }
    // 吃到食物
    checkEat(x:number, y:number){
        if (this.food.X === x && this.food.Y === y) {
            this.food.change()
            this.scorePanel.addScore()
            this.snake.addBody()
        }
    }
}
export default GameControl